package com.google.code.msgbooster.batch.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.google.appengine.api.datastore.Key;
import com.google.code.msgbooster.batch.Meta;
import com.google.code.msgbooster.batch.detector.Clip;
import com.google.code.msgbooster.batch.detector.Core;
import com.google.code.msgbooster.batch.detector.Result;
import com.google.code.msgbooster.core.DB;
import com.google.code.msgbooster.core.Service;
import com.google.code.msgbooster.model.extension.Collector;
import com.google.code.msgbooster.model.extension.Guide;
import com.google.code.msgbooster.model.extension.Relationship;
import com.google.code.msgbooster.model.extension.Stack;
import com.google.code.msgbooster.model.extension.Transponder;

public final class Adapter extends Meta {

	public static List<Result> collect(List<Guide> guides) {
		List<Result> results = new ArrayList<Result>();
		for (Guide guide : guides) {
			Core detector = (Core) Service.getBean(guide.getDetector());
			Result result = detector.get(guide);
			if (result.isSuccess())
				results.add(result);
		}
		return results;
	}

	public static void execute(Relationship relationship) {
		Collector collector = (Collector) DB.select(getPersistenceManager(),
				Collector.class, relationship.getCollector());
		Set<Key> guideKeys = collector.getGuide();
		List<Guide> guides = new ArrayList<Guide>();
		for (Key key : guideKeys)
			guides.add((Guide) DB.select(getPersistenceManager(), Guide.class, key));

		Transponder transponder = (Transponder) DB.select(
				getPersistenceManager(), Transponder.class,
				relationship.getTransponder());
		Set<Key> consumerKeys = transponder.getConsumer();

		List<Result> results = collect(guides);
		Date date = new Date();
		for (Result result : results) {
			List<Clip> clips = result.getClips();
			for (Clip clip : clips) {
				for (Key key : consumerKeys) {
					Stack stack = new Stack();
					stack.setContent(clip.getContent());
					stack.setResource(clip.getResource());
					stack.setFixedLink(clip.getFixedLink());
					stack.setConsumer(key);
					stack.setCreateTime(date);
				}
			}
		}
	}
}
